import * as THREE from '../../build/three.module.js';
import {
  OrbitControls
} from '../../jsm/controls/OrbitControls.js';

const scene = new THREE.Scene();

/**
 * 数据纹理对象
 *    通过程序来生成纹理贴图图像
 */
const geo = new THREE.PlaneGeometry(128, 128);
// 创建纹理对象的像素数据
const width = 32;
const height = 32;
const size = width * height;
const data = new Uint8Array(size * 3); // size * 3 是占用的内存字节数
for(let i = 0; i < size * 3; i += 3) {
  // 随机分配RGB值
  data[i] = 255 * Math.random();
  data[i + 1] = 255 * Math.random();
  data[i + 2] = 255 * Math.random();
}
// 创建数据纹理对象
const txr = new THREE.DataTexture(data, width, height, THREE.RGBFormat);
txr.needsUpdate = true;
console.log(txr.image);
const mat = new THREE.MeshPhongMaterial({
  map: txr
});
const plane = new THREE.Mesh(geo, mat);
plane.translateX(-150);
scene.add(plane);

// 设置透明分量
const dataA = new Uint8Array(size * 4); // size * 4 带alpha分量的RGB模型占用字节数
for(let i = 0; i < size * 4; i += 4) {
  // 随机分配RGBA值
  dataA[i] = 255 * Math.random();
  dataA[i + 1] = 255 * Math.random();
  dataA[i + 2] = 255 * Math.random();
  dataA[i + 3] = 255 * .5; // 统一半透明
}
// 创建数据纹理对象
const txrA = new THREE.DataTexture(dataA, width, height, THREE.RGBAFormat); // 带透明通道格式
txrA.needsUpdate = true;
console.log(txrA.image);
const matA = new THREE.MeshPhongMaterial({
  map: txrA
});
const planeA = new THREE.Mesh(geo, matA);
planeA.translateX(150);
scene.add(planeA);

const al = new THREE.AmbientLight(0xffffff);
scene.add(al);
const k = innerWidth / innerHeight,
      s = 400,
      camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 10000);
camera.position.set(0, 0, 400);
camera.lookAt(scene.position);
const renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0xaaaaaa);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
new OrbitControls(camera, renderer.domElement);
(function render() {
  renderer.render(scene, camera);
  requestAnimationFrame(render);
})();